<?php
namespace app\wechat\controller;

use think\Request;
use think\Cookie;
use think\View;
use think\Log;

import('phpqrcode/phpqrcode', VENDOR_PATH);
import('weixin/weixin', VENDOR_PATH);

//微信appid
define('WXAPPID','wxd65849ebe359e61e');
//微信AppSecret
define('APPSECRET','414fb50745e442239a88394db542fc9d');
session_start();
/**
 * 接口服务
 * 工行·蚂蚁·商户 聚合支付
 *
 */
class IcbcPay extends Common
{
    // 定义全局常量
    protected $config;
    //dev开发环境
    protected $env = APP_ENV;

    public function __construct() {
        parent::__construct();
        $this->config = config('IcbcPay.' . $this->env);

    }

    /**
     * 下单页面
     *
     */
    public function payOrder($params){

        //判断用户是否登录
        if (!session('username')) {

            session('p_id',$params['p_id']);
            session('qrcode_id',$params['qrcode_id']);
            return view('pay/paylogin');
        }

        //验证信息
        if(empty($params['order_num']) || empty($params['p_id'])){
            return $this->parse_data(['code' => 5000, 'msg' => '数据不能为空']);
        }

        // 获取机构下课程
        $partnerProduct = $this->getWS('credit', 'Aggregate@getPartnerProduct', ['p_id'=>$params['p_id']]);
        if($partnerProduct['status'] != '2000'){
            return $this->parse_data(['code' => 5000, 'msg' => '查询机构课程失败']);
        }
        //账单金额必须在课程所设置的金额范围
        if($params['p_set_amount']==0 || $params['p_set_amount'] < $partnerProduct['result'][0]['p_min_amt'] || $params['p_set_amount'] > $partnerProduct['result'][0]['p_max_amt']){
            return $this->parse_data(['code' => 5000, 'msg' => '此课程金额需在'.$partnerProduct['result'][0]['p_min_amt'].'-'.$partnerProduct['result'][0]['p_max_amt'].'范围']);
        }

        //验证订单重复
        $orderInfo = $this->getWS('credit', 'Aggregate@getOrderList', ['order_num'=>$params['order_num']]);

        if ($orderInfo['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '支付失败,请联系管理员']);
        }
        if(!empty($orderInfo['result'])){
            return $this->parse_data(['code' => 5000,'msg' => '下单失败,请刷新重试！']);
        }

        //如果修改过价格，蚂蚁账单就按修改过的价格来。
        session('set_amount',$params['p_set_amount']);

        // 记录支付流水
        $transactionPay = array(
            'order_type'        => '1',//订单类型：1、聚合支付，2机构充值。3首付
            'channel'           => '4',//第三方通道：1学通宝，2招商 3工商4易宝
//            'appid'             => $partnerProduct['result'][0]['partner_yee_no'],//商户报备号
            'appid'             => '10026053357',//商户报备号
            'u_code'            => session('uid'),//客户编号
            'partner_id'        => $partnerProduct['result'][0]['partner_id'],//商户id
            'partner_name'      => $partnerProduct['result'][0]['partner_name'],//商户名称
            'order_num'         => $params['order_num'],//订单号
            'services'          => '',//服务类型
            'amount'            => $params['p_set_amount'],//交易金额
            'product_id'        => $partnerProduct['result'][0]['p_id'],//课程id
            'product_name'      => $partnerProduct['result'][0]['p_name'],//产品名称
            'name'              => '',//姓名
            'phone'             => session('username'),//手机号
            'note'              => '',//备注
            'status'            => '1000',//状态：1000初始，2000成功，3000等待，4000失败
            'add_time'          => date('Y-m-d H:i:s'),//下单时间
            'clientip'          => getenv("REMOTE_ADDR"),//请求IP地址
            'open_id'           => $params['openid'],//微信用户唯一标识 session('openid')
            'sales_name_id'     => $params['qrcode_id'],
        );
        
        $partnersOrder = $this->getWS('credit', 'PartnersOrder@partnerInsert', $transactionPay);

        if ($partnersOrder['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '下单失败,请联系管理员']);
        }
        //跳转选择支付页面
        return $this->parse_data(['code' => 2000, 'msg' => '下单成功', 'data'=> ['order_num' => $params['order_num']]]);
    }

    /**
     * 保险资料提交页
     *
     **/
    public function insuranceInfo()
    {
        if(!empty($_POST)){
            $params = request()->param();
            $params = json_decode($params['datas'],true);
            $params['u_code'] = session('uid');

            // 保存投保人信息
            $userInsurance = $this->getWS('credit', 'Insurance@saveInsuranceData', $params);
            //预投保
            $res = $this->getWS('channel', 'Insurance@preInsurance', $userInsurance['result']);

            //验证是否可以投保
            if($res['status'] == '0000'){
                //投保成功更新预投保状态
                $this->getWS('credit', 'Insurance@updatePreInsuranceStatus', ['reqt_id'=>$userInsurance['result']['reqt_id'],'pre_insurance_status'=>1]);

                return $this->parse_data(['code' => 2000, 'msg' => '预投保成功']);
            }else{
                $this->getWS('credit', 'Insurance@updatePreInsuranceStatus', ['reqt_id'=>$userInsurance['result']['reqt_id'],'pre_insurance_status'=>2]);

                return $this->parse_data(['code' => 5000, 'msg' => $res['result']]);
            }
        }else{
            $params = request()->param();
            //判断订单信息
            if(empty($params['order_num'])){
                return $this->parse_data(['code' => 5000, 'msg' => '订单号信息有误！']);
            }

            return view('pay/insurance_info',['order_num'=>$params['order_num'],'p_id'=>$params['p_id']]);
        }
    }

    /**
     * 选择支付方式信息
     *
    **/
    public function pay()
    {
        $params = request()->param();

        //判断订单信息
        if(empty($params['order_num'])){
            return $this->parse_data(['code' => 5000, 'msg' => '订单号信息有误！']);
        }

        //查询订单
        $orderInfo = $this->getWS('credit', 'Aggregate@getOrderList', ['order_num'=>$params['order_num']]);
        if ($orderInfo['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '下单失败,请联系管理员']);
        }

        //判断是否是微信还是支付宝
        if(IsWeixinOrAlipay() == 'WeiXin'){


            //TODO 获取openid（现在这里没有openid会支付不了，）product.openid
            if(empty($params['openid'])){
                $redirect_uri = "http://release.weixin.mayi121.com/product.openid?order_num=".$params['order_num'];
                $scope = "snsapi_base";
                header("Location: https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd65849ebe359e61e&redirect_uri=".$redirect_uri."&response_type=code&scope=".$scope."&state=STATE#wechat_redirect");
                exit;
            }

            $orderW = array(
                'id'                => $orderInfo['result'][0]['id'],
                'open_id'           => $params['openid'],
                'updated_date'      => date('Y-m-d H:i:s'),
            );
            //更新交易订单
            $openArr = $this->getWS('credit', 'PartnersOrder@partnerInsert', $orderW);
            Log::write($openArr, '首付接收参数2', true, 'yeesf/');

//            $services = 1;
            $services = 3;
        }else if(IsWeixinOrAlipay() == 'Alipay'){
            $services = 3;
        }else{
            $services = 3;
        }

        //验证是否有账期
        $partnerProduct = $this->getWS('credit', 'Aggregate@getPartnerProduct', ['p_id'=>$orderInfo['result'][0]['product_id']]);

        $data = array(
            'sh_partner_id'=>$orderInfo['result'][0]['partner_id'],
            'sh_type' => '1,2,3,4',
            'sh_status'=> '20',
        );
        //查询是否开通金融机构账单
        $serviceReview = $this->getWS('credit', 'PartnersOrder@serviceReviewSelect', $data);
        if($serviceReview['status'] == 2000 && $partnerProduct['result'][0]['p_is_fenqi'] == 1){
            $sh_status = '2';
        }
        //TODO 验证工蚂付是否过期，过期停止使用服务。
        if (strtotime(date('Y-m-d H:i:s')) > strtotime($partnerProduct['result'][0]['partner_end_time'])) {
            $end_time = 2;
            $services = 5;
//            return $this->parse_data(['code' => 5000, 'msg' => '支付出现问题，请联系机构！']);
        }

        //自动选择课程需要
        session('p_id',$orderInfo['result'][0]['product_id']);
        session('p_name',$partnerProduct['result'][0]['p_name']);
        // 之所以加这个session是因为 Product.partnerFunds 这个方法要用，为什么要这么用，不是很清楚，不建议
        session('partner_id', $orderInfo['result'][0]['partner_id']);
        // type 字段为区分支付流程 同步通知路径
        return view('pay/select_pay',['data'=>$orderInfo['result'][0],'services'=>$services,'end_time'=>$end_time,'sh_status'=>$sh_status,'type'=>$params['type'],'partnerProduct'=>$partnerProduct['result'][0]]);
    }

    /**
     * 确认支付页面(易宝)
     *
     **/
    public function yeeDeterminePay($params){

        //判断用户是否登录
        if (!session('username')) {
            return $this->parse_data(['code' => 5003, 'msg' => '请先登录']);
        }
        //验证信息
        if(empty($params['order_num']) || empty($params['u_code']) || empty($params['services'])){
            return $this->parse_data(['code' => 5000, 'msg' => '数据不能为空']);
        }

        //查询订单
        $orderInfo = $this->getWS('credit', 'Aggregate@getOrderList', ['order_num'=>$params['order_num']]);
        if ($orderInfo['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '支付失败,请联系管理员']);
        }

        //验证工蚂付过没过期
        $partnerProduct = $this->getWS('credit', 'Aggregate@getPartnerProduct', ['p_id'=>$orderInfo['result'][0]['product_id']]);
        //TODO 验证工蚂付是否过期，过期停止使用服务。
        if (strtotime(date('Y-m-d H:i:s')) > strtotime($partnerProduct['result'][0]['partner_end_time'])) {
            return $this->parse_data(['code' => 5000, 'msg' => '支付出现问题，请联系机构！']);
        }

        //判断是否是微信还是支付宝
        if($params['services'] == 1){
            $services = $params['services'];
            $payType = 'WECHAT';
            $payTool = 3;
            $payRate = 0.68;
        }else if($params['services'] == 2){
            $services = $params['services'];
            $payType = 'ALIPAY';
            $payTool = 1;
            $payRate = 0.68;
        }else if($params['services'] == 3){
            $services = $params['services'];
            $payType = 'UPOP';
            $payRate = 0.45;
        }else{
            return $this->parse_data(['code' => 5000, 'msg' => '请选择支付方式！']);
        }

        //根据支付类型  扣除易宝交易手续费  进行订单分账
        $partnerChannel = $this->getWS('credit', 'partners@partnerChannel', ['partner_id' => $orderInfo['result'][0]['partner_id']]);
        if ($partnerChannel['status'] != '2000' || empty($partnerChannel['result']['partner_yee_no'])) {
            return $this->parse_data(['code' => '5000', 'msg' => '查询错误']);
        }
        $yeeAmt = sprintf('%.2f',$orderInfo['result'][0]['amount']* $payRate / 100);  //计算易宝手续费金额
        $partner_amout = $orderInfo['result'][0]['amount'] - $yeeAmt;

        $divide_detail_info = [
            [
                'ledgerNo' => '10025852870', //机构商编
//                'ledgerNo' => $partnerChannel['result']['partner_yee_no'], //机构商编
                'ledgerName' => $partnerChannel['result']['partner_name'],
                'amount' => sprintf("%1\$.2f", $partner_amout),
            ]
        ];
        $partnersOrder = $this->getWS('credit', 'PartnersOrder@partnerInsert', ['id' => $orderInfo['result'][0]['id'], 'divide_detail_info' => json_encode($divide_detail_info)]);

        //选择支付类型，1微信2支付宝，3银联
        $redirectUrl = "http://release.weixin.mayi121.com/paySuccess?order_num=".$orderInfo['result'][0]['order_num'];
        $redirectUrl = empty($params['redirectUrl']) ? $redirectUrl : $params['redirectUrl'];
        if($services == '3'){
            //调用易宝接口支付
            $yeeData = array(
                'merchantNo'    => $orderInfo['result'][0]['appid'],//子商编（业务上是必须参数，收单商户商编）10015004197
                'orderId'       => $orderInfo['result'][0]['order_num'],//商户请求号（业务上是必须参数，商户订单号）
                'orderAmount'   => $orderInfo['result'][0]['amount'],//总金额（单位：分）
                'userNo'        => $orderInfo['result'][0]['u_code'],//用户标识
                'redirectUrl'   => $redirectUrl, //支付成功回显页面
                'productName'   => $orderInfo['result'][0]['product_name'], // 产品名称
                'productDesc'   => $orderInfo['result'][0]['product_name'], // 产品描述
                'divide_detail_info' => json_encode($divide_detail_info)  //分账明细
            );
            Log::write($yeeData, '易宝接口返回4', true, 'yee/');
            $yeePay = $this->getWS('channel', 'Yeepay@payment', $yeeData);
            Log::write($yeePay, '易宝接口返回5', true, 'yee/');

            if ($yeePay['status'] != '2000') {
                return $this->parse_data(['code' => 5000, 'msg' => '支付失败!','closeCurrTab'=>false]);
            }

            //成功后写入同步信息
            $data = array(
                'order_num'         => $orderInfo['result'][0]['order_num'],
                'status'            => '3000',
                'services'          => $services,
                'synchronize_info'  => serialize($yeePay),//同步信息
            );
            $updateOrder = $this->getWS('credit', 'Aggregate@updateOrderStatus', $data);
            if($updateOrder['status'] != "2000"){
                return $this->parse_data(['code' => 5000, 'msg' => '同步信息写入失败!','closeCurrTab'=>false]);
            }

            //处理接受到的信息（因为这里&符号到html前端会转义，需要处理下。）
            $url = strtr($yeePay['result'], '&', '&amp;');

            return $this->parse_data(['code' => 2000, 'data' => ['pay' => $url]]);
        }else if($services == 1 || $services == 2){
            //调用易宝接口支付
            $yeeData = array(
                'merchantNo'    => $orderInfo['result'][0]['appid'],//子商编（业务上是必须参数，收单商户商编）10015004197
                'orderId'       => $orderInfo['result'][0]['order_num'],//商户请求号（业务上是必须参数，商户订单号）
                'orderAmount'   => $orderInfo['result'][0]['amount'],//总金额（单位：分）
                'userNo'        => $orderInfo['result'][0]['u_code'],//用户标识
                'openId'        => $orderInfo['result'][0]['open_id'],//用户OPENID
                'payTool'       => $payTool,//1（用户扫码支付）2（商户扫码支付）3（公众号支付）4（支付宝生活号）5（微信小程序）6（SDK支付）
                'payType'       => $payType,
                'redirectUrl'   => $redirectUrl, //支付成功回显页面
                'productName'   => $orderInfo['result'][0]['product_name'], // 产品名称
                'productDesc'   => $orderInfo['result'][0]['product_name'], // 产品描述
                'divide_detail_info' => json_encode($divide_detail_info)  //分账明细
            );

            Log::write($yeeData, '易宝接口返回1', true, 'yee/');
            $yeePay = $this->getWS('channel', 'Yeepay@pay', $yeeData);
            Log::write($yeePay, '易宝接口返回2', true, 'yee/');

            if ($yeePay['status'] != '2000') {
                return $this->parse_data(['code' => 5000, 'msg' => '支付失败!','closeCurrTab'=>false]);
            }

            //成功后写入同步信息
            $data = array(
                'order_num'         => $orderInfo['result'][0]['order_num'],
                'status'            => '3000',
                'services'          => $services,
                'synchronize_info' => serialize($yeePay),//同步信息
            );
            $updateOrder = $this->getWS('credit', 'Aggregate@updateOrderStatus', $data);
            if($updateOrder['status'] != "2000"){
                return $this->parse_data(['code' => 5000, 'msg' => '支付失败!','closeCurrTab'=>false]);
            }

            //如果是微信返回前端处理微信支付
            if($yeePay['result']['payType'] == 'WECHAT'){

                $wechat = array(
                    'resultData'=>json_decode($yeePay['result']['resultData'],true),
                    'order_num'=>$orderInfo['result'][0]['order_num'],
                );
                Log::write($wechat, '易宝接口返回3', true, 'yee/');
                return $this->parse_data(['code' => 2000, 'data' => ['pay' => $wechat]]);
            }else{//支付宝
                return $this->parse_data(['code' => 2000, 'data' => ['pay' => $yeePay['result']['resultData']]]);
            }
        }else{
            return $this->parse_data(['code' => 5000, 'msg' => '失败!','closeCurrTab'=>false]);
        }

    }

    /**
     * 确认支付页面(工行暂时不用)
     *
    **/
    public function determinePay($params){

        //判断用户是否登录
        if (!session('username')) {
            return $this->parse_data(['code' => 5003, 'msg' => '请先登录']);
        }

        if(empty($params['order_num'])){
            return $this->parse_data(['code' => 5000, 'msg' => '订单信息错误！']);
        }

        //验证信息
        if(empty($params['order_num']) || empty($params['u_code']) || empty($params['services'])){
            return $this->parse_data(['code' => 5000, 'msg' => '数据不能为空']);
        }

        //验证用户是否真实性


        //查询订单
        $orderInfo = $this->getWS('credit', 'Aggregate@getOrderList', ['order_num'=>$params['order_num']]);
        if ($orderInfo['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '支付失败,请联系管理员']);
        }

        $order = $orderInfo['result'][0]['order_num'];

        //如果点击确认支付，生成的订单号在工行那边支付，未支付返回页面，这里需要重新生成订单。
        if($orderInfo['result'][0]['status'] == '3000'){ //3000是同步状态

            //生成订单号
            $order_new = 'MY'.date('YmdHis').mt_rand(1000,9999);
            $data = array(
                'order_num'         => $params['order_num'],
                'order_num1'        => $order_new
            );

            $updateOrder = $this->getWS('credit', 'Aggregate@updateOrderStatus', $data);

            if($updateOrder['status'] != "2000"){
                $result = ['code' => 5000, 'msg' => '参数错误'];
                return $this->parse_data($result);
            }

            $order = $order_new;
        }

        //判断是否是微信还是支付宝
        if(IsWeixinOrAlipay() == 'WeiXin'){
            $services = 1;
        }else if(IsWeixinOrAlipay() == 'Alipay'){
            $services = 2;
        }else{
            return view('pay/error',['data'=>'暂不支持该类型支付！请选择微信或支付宝！']);
        }

        //调用工行接口支付
        $data = array(
            'out_trade_no'      => $order,//订单号
            'goods_body'        => $orderInfo['result'][0]['product_name'],//商品描述（课程名称）
            'mer_id'            => $orderInfo['result'][0]['appid'],//商户号
            'order_amount'      => $orderInfo['result'][0]['amount']*100,//总金额（单位：分）
            'return_url'        => "http://test.weixin2.mayi121.com/paySuccess?order_num=".$order, //支付成功回显页面
            'spbill_create_ip'  => $orderInfo['result'][0]['clientip'], //终端ip
            'services'          => $services,//
        );

        $icbcPay = $this->getWS('channel', 'Icbc@icbcPay', ['data' => $data]);

        Log::write($icbcPay, '接口返回', true, 'icbc/');

        if ($icbcPay['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '支付失败,请联系管理员']);
        }

        return $this->parse_data(['code' => 2000, 'data' => ['pay' => $icbcPay['result']]]);
    }

    /**
     * 获取微信的openid
     *
    */
    public function getOpen(){

        $code = Request::instance()->get();
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".WXAPPID."&secret=".APPSECRET."&code=".$code."&grant_type=authorization_code";
        $result = $this->curlOpen($url);
        $res = json_decode($result, true);

        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$res['access_token']."&openid=".$res['openid']."&lang=zh_CN";
        $result = $this->curlOpen($url);
        $res = json_decode($result,true);

        echo $res;exit;
    }

    /**
     * 获取微信的openid
     */
    public function getOpenId()
    {
        // 获取code参数
        $params = request()->param();

        if(empty($params['partner_id'])){
            return view('pay/receipt',['data' => '参数错误!']);
        }

        if(empty($params['openid'])){
            $redirect_uri = config('wechat.'. APP_ENV)['weburl']."/getReceiptOpenId?partner_id=".$params['partner_id'];
            $scope = "snsapi_base";
            header("Location: https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd65849ebe359e61e&redirect_uri=".$redirect_uri."&response_type=code&scope=".$scope."&state=STATE#wechat_redirect");
            exit;
        }
        Log::write($params, '信息', true, 'weixins/');

        //获取微信用户信息
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$params['access_token']."&openid=".$params['openid']."&lang=zh_CN";
        $result = $this->curlOpen($url);
        $resInfo = json_decode($result,true);

        Log::write($resInfo, '信息1', true, 'weixins/');

//        $params['partner_id'] = '26';
//        $resInfo['openid'] = 'oHRftt6_uBpTa1q81GcHl1OIMwf0';

        if(!empty($params['openid'])){

            //查询是否有知否已绑定过收款码
            $data = array(
                'partner_id'=>$params['partner_id'],
                'open_id'   => $params['openid'],
                'qrcode_type'=> 1,
            );

            $qrcode = $this->getWS('credit', 'PartnersQrcode@partnerSelect', $data);
            if ($qrcode['status'] == '2000') {
                return view('pay/receipt',['data' => '该微信已添加!']);
            }

            //查询绑定收款码人数
            $data = array(
                'partner_id'=> $params['partner_id'],
                'qrcode_type'=> 1,
            );
            $partnersQrcode = $this->getWS('credit', 'PartnersQrcode@partnerSelect', $data);
            $codeNum = count($partnersQrcode['result']);
            if($codeNum >= 5){
                return view('pay/receipt',['data' => '只能添加5个提醒人员']);
            }

            $data = array(
                'partner_id'       => $params['partner_id'],//机构id
                'product_id'        => '',//课程id
                'qrcode_type'      => 1,//类型1、收款二维码，2、课程二维码
                'qrcode_url'       => '',//二维码连接url
                'name'             => '',//姓名
                'phone_number'     => '',//手机号
                'open_id'          => $params['openid'],//微信用户唯一标识
                'wechat_name'      => $resInfo['nickname'],//微信名称
                'wechat_info'      => serialize($resInfo),//微信同步返回信息
                'add_time'         => date('Y-m-d H:i:s'),//添加时间
            );
            //插入二维码信息
            $qrcode = $this->getWS('credit', 'PartnersQrcode@qrcodeInsert', $data);
            if ($qrcode['status'] != '2000') {
                return view('pay/receipt',['data' => '添加失败']);
            }
        }

        return view('pay/receipt',['data' =>'您已添加成功！']);
    }


    //curl函数
    public function curlOpen ($url, $cfg)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        if ($cfg['ssl']) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $cfg['post']);
        $result = curl_exec($ch);
        $info = curl_getinfo($ch);
//        print_r($info);exit;
        curl_close($ch);

        return $result;
    }

    /**
     * 返回调用,不用这个parse_data，是因为他返回的还得转换
     *
     */
    public function outputJson($data, $exit = false)
    {
        ob_end_clean();
        isset($GLOBALS['setToken']) ? $data = array_merge($data, $GLOBALS['setToken']) : null;
        $json = json_encode($data);
        print_r($json);
        if ($exit)
            exit;
    }


    /**
     * 微信付款成功页面。
     *
     */
    public function wxPaySuccess()
    {

        $data = Request::instance()->get();
        //获取蚂蚁订单号
        $orderNo = $data['orderNo'];

        $partnerWhere = array(
            'order_num' => $orderNo,
        );
        $orderPartnerInfo = $this->getWS('credit', 'PartnersOrder@orderPartnerInfo', $partnerWhere);

        $return = array(
            'amount'=>$orderPartnerInfo['result']['amount'],
            'payee'=> $orderPartnerInfo['result']['partner_name'],
            'paytype'=> '微信',
            'paytime'=> $orderPartnerInfo['result']['add_time'],
        );
        return view('pay/zsOrderSuccess',['data' => $return]);
    }

    /**
     * 微信付款JS-SDK
     *
     */
    public function getSignature()
    {
        $data = Request::instance()->get();

        //生成wx.config
        $weixin =  new \Lib_Weixin();
        $tokenarr = $weixin->getAccessToken(WXAPPID, APPSECRET);
        $jsapi_ticket = $weixin->getJsApiTicket($tokenarr['access_token']);
        $nonceStr = getRandomChar();
        $time = time();
        $signature = sha1("jsapi_ticket=".$jsapi_ticket['ticket']."&noncestr=".$nonceStr."&timestamp=".$time."&url=".$data['url']);

//        $wx_config = "wx.config({
//						debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
//						appId: '".WXAPPID."', // 必填，公众号的唯一标识
//						timestamp: ".$time.", // 必填，生成签名的时间戳
//						nonceStr: '".$nonceStr."', // 必填，生成签名的随机串
//						signature: '".$signature."',// 必填，签名，见附录1
//						jsApiList: ['closeWindow'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
//					});";
//        print_r($wx_config);exit;
        $wx_config = array(
            'appId'     => WXAPPID,
            'timestamp' => $time,
            'nonceStr'  => $nonceStr,
            'signature' => $signature,
        );

        $out = array(
            'status' => 2000,
            'msg' => '成功',
            'result' => $wx_config,
        );
        $this->outputJson($out,true);

    }

    /**
     * 微信获取位置JS-SDK
     *
     */
    public function getLocation()
    {
        $data = Request::instance()->get();

        //生成wx.config
        $weixin =  new \Lib_Weixin();
        $tokenarr = $weixin->getAccessToken(WXAPPID, APPSECRET);
        $jsapi_ticket = $weixin->getJsApiTicket($tokenarr['access_token']);
        $nonceStr = getRandomChar();
        $time = time();
        $signature = sha1("jsapi_ticket=".$jsapi_ticket['ticket']."&noncestr=".$nonceStr."&timestamp=".$time."&url=".$data['url']);

//        $wx_config = "wx.config({
//						debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
//						appId: '".WXAPPID."', // 必填，公众号的唯一标识
//						timestamp: ".$time.", // 必填，生成签名的时间戳
//						nonceStr: '".$nonceStr."', // 必填，生成签名的随机串
//						signature: '".$signature."',// 必填，签名，见附录1
//						jsApiList: ['closeWindow'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
//					});";
//        print_r($wx_config);exit;
        $wx_config = array(
            'appId'     => WXAPPID,
            'timestamp' => $time,
            'nonceStr'  => $nonceStr,
            'signature' => $signature,
        );

        $return = array(
            'status'=>2000,
            'msg'=> '成功',
            'result'=> $wx_config,
        );
        return view('pay/location',['data' => $return]);

    }


    /*
     * 扫码跳转机构课程页面
     */
    public function showProcuct()
    {
        // 获取参数
        $params = request()->param();
        $result = $this->getWS('credit', 'Aggregate@getPartnerProduct', ['partner_id' => 26]);
        return $this->parse_data(['code'=>2000,'msg'=>'查询机构课程成功','data'=>$result]);
    }

    /**
     * 扫码进入机构课程选择页面
     */
    public function productPay()
    {
        // 获取机构唯一标识
        $params = request()->param();

        if($params['token_id'] != substr(md5('MYBLJHZF'), 0, 16) || empty($params['partner_id'])){
            return view('pay/error',['data'=>'非法请求数据']);
        }

        // 获取机构下课程
        $partnerProduct = $this->getWS('credit', 'Aggregate@getPartnerProduct', ['partner_id'=>base64_decode($params['partner_id'])]);
        if($partnerProduct['status'] != '2000'){
            return view('pay/error',['data'=>'查询机构课程失败']);
        }

        session('partner_id', $partnerProduct['result'][0]['partner_id']);
        session('partner_k12', $partnerProduct['result'][0]['partner_k12']);
        session('partner_name', $partnerProduct['result'][0]['partner_name']);
        session('qrcode_id', $params['qrcode_id']);

        return view('pay/product_pay',['data'=>$partnerProduct['result'],'token_id'=>substr(md5(date('Y-m-d').'MYBL'), 0, 16),'qrcode_id'=>$params['qrcode_id']]);
    }

    /**
     * 扫码进入机构课程选择页面(统一收款码)
     */
    public function productSelect()
    {

        // 获取机构唯一标识
        $params = request()->param();
        $params       = $this->xaddslashes($params);

        if($params['token_id'] != substr(md5('MYBLJHZF'), 0, 16) || empty($params['qr_code'])){
            return view('pay/error',['data'=>'非法请求数据']);
        }
        //查询是否绑定
        $qRcodeAct = $this->getWS('credit', 'Aggregate@getQRcodeAct', ['qr_code'=>base64_decode($params['qr_code'])]);
        if($qRcodeAct['status'] != '2000'){
            return view('pay/error',['data'=>'查询机构二维码失败']);
        }

        //判断是否绑定，如果没绑定跳转绑定，绑定过了，直接用编号查询partner_id
        if($qRcodeAct['result']['qr_status'] == 2){
            return view('/agreement/pQrCode',['qr_code'=>$params['qr_code'],'token_id'=>$params['token_id']]);
        }

        // 获取机构下课程
        $partnerProduct = $this->getWS('credit', 'Aggregate@getPartnerProduct', ['partner_id'=>$qRcodeAct['result']['partner_id']]);
        if($partnerProduct['status'] != '2000'){
            return view('pay/error',['data'=>'查询机构课程失败']);
        }

        session('partner_id', $partnerProduct['result'][0]['partner_id']);
        session('partner_k12', $partnerProduct['result'][0]['partner_k12']);
        session('partner_name', $partnerProduct['result'][0]['partner_name']);

        return view('pay/product_pay',['data'=>$partnerProduct['result'],'token_id'=>substr(md5(date('Y-m-d').'MYBL'), 0, 16)]);
    }

    /**
     * 扫码进入机构选择页面->支付
     */
    public function productPayNext()
    {
        // 获取课程id
        $params = request()->param();

        // 验证参数
        if($params['token_id'] != substr(md5(date('Y-m-d').'MYBL'), 0, 16) || empty($params['p_id'])){
            return view('pay/error',['data'=>'非法请求数据']);
        }
        session('p_id',$params['p_id']);
        if($params['qrcode_id']){
            session('qrcode_id',$params['qrcode_id']);
            $qrco = "&qrcode_id=".$params['qrcode_id'];
        }


        // 判断用户是否已登录
        if(!session('username')){ // 登录
            return view('pay/paylogin');
        }else{
            return redirect('/confirmOrder?p_id='.$params['p_id'].$qrco);
        }
    }

    /**
     * 扫码进入登录->课程
     */
    public function productLogin()
    {
        // 获取课程id
        $params = request()->param();
        $red = "/productPayNext?p_id=".base64_encode($params['p_id'])."&token_id=".substr(md5(date('Y-m-d').'MYBL'), 0, 16)."&qrcode_id=".$params['qrcode_id'];
        return redirect($red);
    }

    /**
     * 登录后确认订单页
     */
    public function confirmOrder()
    {
        // 获取机构唯一标识
        $params = request()->param();

        //判断用户是否登录
        if (!session('username')) {

            session('p_id',$params['p_id']);
            session('qrcode_id',$params['qrcode_id']);
            return view('pay/paylogin');
        }

//        session('uid', 'U18101967996');
//        session('username', '18301099036');
//        session('openid','123456');
//        $params['openid'] = 'oHRftt6_uBpTa1q81GcHl1OIMwf0';

        if(IsWeixinOrAlipay() == 'WeiXin'){
            //TODO 获取openid（上线后干掉，现在这里没有openid会支付不了，）
            if(empty($params['openid'])){
                $redirect_uri = "http://release.weixin.mayi121.com/order.openid?p_id=".$params['p_id'];
                $scope = "snsapi_base";
                header("Location: https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd65849ebe359e61e&redirect_uri=".$redirect_uri."&response_type=code&scope=".$scope."&state=STATE#wechat_redirect");
                exit;
            }
        }else if(IsWeixinOrAlipay() == 'Alipay'){

        }else{

        }

        // 获取机构下课程
        $partnerProduct = $this->getWS('credit', 'Aggregate@getPartnerProduct', ['p_id'=>base64_decode($params['p_id'])]);

        if($partnerProduct['status'] != '2000'){
            return view('pay/error',['data'=>'查询机构课程失败']);
        }

        session('p_id',base64_decode($params['p_id']));
        session('p_name',$partnerProduct['result'][0]['p_name']);

        //生成订单号
        $order_num = 'MY'.date('YmdHis').mt_rand(1000,9999);

        //计算保险费用
        $productInfo = $this->getWS('credit', 'Product@productInfo', ['pid'=>base64_decode($params['p_id'])]);
        $partnerProduct['result'][0]['p_insurance_price'] = $productInfo['result']['insurance_user_pay'];
        $partnerProduct['result'][0]['is_show'] = $productInfo['result']['is_show'];

        return view('pay/confirm_order',['data'=>$partnerProduct['result'],'order_num'=>$order_num,'qrcode_id'=>$params['qrcode_id'],'openid'=>$params['openid']]);
    }

    /**
     * 支付订单列表
     */
    public function orderPay()
    {
        // 获取用户code
        $u_code = session('uid');
        $orderPay = $this->getWS('credit', 'Aggregate@getOrderList', ['u_code'=>$u_code,'order_type'=>'1,3,6','is_exist_insurance'=>1]);

        if($orderPay['status'] != '2000'){
            return view('pay/error',['data'=>'查询支付订单列表失败']);
        }

        //判断是否存在订单
        if(!empty($orderPay['result'])){
            $data = $orderPay['result'];
        }else{
            $data = '';
        }
        if(!empty($data)) {
            foreach ($data as $key => $value) {
                $data[$key]['pay_link'] = 'pay';
                if ($value['order_type'] == 6) {
                    $data[$key]['pay_link'] = 'pay';
                }
                if($value['order_type'] == 1){
                    //查询工蚂付订单中是否存在保险
                    if($value['iid']){
                        $data[$key]['insuranceInfo'] = 1;
                    }else{
                        $data[$key]['insuranceInfo'] = 2;
                    }
                }
            }
        }

        return view('pay/order_pay',['data'=>$data]);
    }

    /**
     * 支付失败，待支付订单详情页
     */
    public function failPayDetail()
    {
        $params = request()->param();
        // 获取订单号
        if(!isset($params['order_num']) || empty($params['order_num'])){
            return view('pay/error',['data'=>'参数错误']);
        }
        $order_num = $params['order_num'];
//        $order_num = 'MY201811091500135372';
        // 获取支付失败详情页   状态 1000初始，2000成功，3000等待，4000失败',
        $fail_detail = $this->getWS('credit', 'Aggregate@getOrderList', ['order_num'=>$order_num,'status'=>'4000']);

        if($fail_detail['status'] == '2000'){
            $partner_id = $fail_detail['result'][0]['partner_id'];
            $p_name = $fail_detail['result'][0]['product_name'];
        }else{
            return view('pay/error');
        }

        //查询课程是否有账期
        $periodResult = $this->getWS('credit', 'product@periodList', ['partner_id' => $partner_id, 'p_name' => $p_name]);
        $isShowPeriod = '';
        if($periodResult['status'] == '2000'){
            if(!empty($periodResult['result'])){
                $isShowPeriod = 1;
            }
        }
        return view('pay/failPayDetail',['data'=>$fail_detail['result'][0],'isShowPeriod'=>$isShowPeriod]);
    }

    /**
     * 支付成功订单详情页
     */
    public function succPayDetail()
    {
        $params = request()->param();
        // 获取订单号
        if(!isset($params['order_num']) || empty($params['order_num'])){
            return view('pay/error',['data'=>'参数错误']);
        }
        $order_num = $params['order_num'];
	
//        $order_num = 'MY201811091500135372';
        // 获取支付成功详情页    状态 1000初始，2000成功，3000等待，4000失败',
        $succ_detail = $this->getWS('credit', 'Aggregate@getOrderList', ['order_num'=>$order_num,'status'=>'2000']);

        if($succ_detail['status'] != '2000'){
            return view('pay/error');
        }

        return view('pay/succPayDetail',['data'=>$succ_detail['result'][0]]);
    }

    /**
     * 支付成功、失败页
     */
    public function paySuccess()
    {
        $params = request()->param();
        
        // 获取订单号
        if(!isset($params['order_num']) || empty($params['order_num'])){
            return view('pay/error',['data'=>'参数错误']);
        }
        sleep(3);
        $order_num = $params['order_num'];
//        $order_num = 'MY201811091500135372';
        // 获取支付成功详情页    状态 1000初始，2000成功，3000等待，4000失败',
        $succ = $this->getWS('credit', 'Aggregate@getOrderList', ['order_num'=>$order_num]);

        if($succ['status'] != '2000'){
            return view('pay/error');
        }

        return view('pay/paySuccess',['data'=>$succ['result'][0]]);
    }

    /**
     * 支付入口页面
     */
    public function payIndex()
    {
        return view('pay/pay_index');
    }

    /**
     * 我的，个人中心
     */
    public function userCenter()
    {
        $params = request()->param();
        //获取订单号
        if(!session('uid')){
            return view('pay/paylogin');
        }
        $u_code = session('uid');

        // 获取支付成功详情页    状态 1000初始，2000成功，3000等待，4000失败',
        $userInfo = $this->getWS('ucenter', 'Users@userInfo', ['u_code'=>$u_code]);

        if($userInfo['status'] != '2000'){
            return view('pay/error');
        }

        //获取保险信息
        $insuranceInfo = $this->getWS('credit', 'Insurance@getInsuranceInfo', ['u_code'=>$this->uid,'pre_insurance_status'=>1,'training_start_time'=>['lt',date('Y-m-d H:i:s',time())],'training_end_time'=>['gt',date('Y-m-d H:i:s',time())],'is_delete'=>2]);
        if(empty($insuranceInfo['result'])){
            $is_insurance = 0;
        }else{
            $condition['u_code']    = $insuranceInfo['result']['u_code'];
            $condition['partner_id']    = $insuranceInfo['result']['partner_id'];
            $condition['product_id']    = $insuranceInfo['result']['p_id'];
            $signInfo = $this->getWS('ucenter', 'users@getSignData', $condition);
            $is_insurance =  empty($signInfo['result']) ? 0 : 1 ;
        }

        return view('pay/userCenter',['data'=>$userInfo['result'],'is_insurance' => $is_insurance]);
    }

    /**
     * 取消订单
     */
    public function cancelOrder($params)
    {
        if(!session('uid')){
            return $this->parse_data(['code'=>'5001','msg'=>'请先登录']);
        }
        // 获取订单号
        foreach(array_keys($params) as $key=>$val){
            if(!in_array($val,['order_num']) || empty($params['order_num'])){
                return $this->parse_data(['code' => 5000, 'msg' => '参数错误！']);
            }
        }

        //取消订单
        $data = array(
            'order_num'         => $params['order_num'],
            'status'            => '5000',
        );
        $updateOrder = $this->getWS('credit', 'Aggregate@updateOrderStatus', $data);

        if($updateOrder['status'] != "2000"){
            $result = ['code' => 5000, 'msg' => '取消失败，请刷新后重试！'];
            return $this->parse_data($result);
        }
        $result = ['code' => 2000, 'msg' => '订单取消成功！'];
        return $this->parse_data($result);
    }


    /**
     * 推送微信信息-聚合支付
     *
     */
    public function sendWeChatInfo(){

        $params = request()->param();
//        $orderInfo['result'][0]['open_id'] = 'oHRftt6_uBpTa1q81GcHl1OIMwf0';
//        $orderInfo['result'][0]['order_num'] = 'MY201811122042563961';
//        $orderInfo['result'][0]['product_name'] = '设计师全能VIP套餐（4合1）';

        //查询订单
        $orderInfo = $this->getWS('credit', 'Aggregate@getOrderList', ['order_num'=>$params['order_num'],'order_type'=>1]);
        if ($orderInfo['status'] == '2000') {

            if($orderInfo['result'][0]['open_id']){

                //推送用户信息
                $data = array(
                    'send_weixin_data' => array(
                        'touser' => $orderInfo['result'][0]['open_id'],//要发给谁
                        //'touser_platform' => 1,//微信1（目前只有微信，写死为1）
                        'template_id' => '0agp55PIHYazsOBYc1dd3lBwoC1BEZkPDbAY5KywUUc',
                        'url'=>'http://test.weixin2.mayi121.com/succPayDetail?order_num='.$orderInfo['result'][0]['order_num'],
                        'topcolor'=>"#FF0000",
                        'data'=>array(
                            'first'=>array('value'=>"付款通知","color"=>"#173177"),
                            'OrderSn'=>array('value'=>$orderInfo['result'][0]['order_num'],"color"=>"#173177"),
                            'OrderAmount'=>array('value'=>$orderInfo['result'][0]['amount'],"color"=>"#173177"),
                            'OrderName'=>array('value'=>$orderInfo['result'][0]['product_name'],"color"=>"#173177"),
                            'remark'=>array('value'=>"\n您订单已成功","color"=>"#173177"),
                        )
                    ),
                );
                $weixin =  new \Lib_Weixin();
                $tokenarr = $weixin->getAccessToken(WXAPPID, APPSECRET);
                $weixin->sendTemplateMessage($tokenarr['access_token'],$data['send_weixin_data']);
            }

            //推送机构绑定人员信息
            $data = array(
                'partner_id'    => $orderInfo['result'][0]['partner_id'],
                'qrcode_type'   => 1,
                'is_delete'     => 2,
            );
            $qrcode = $this->getWS('credit', 'PartnersQrcode@partnerSelect', $data);

            if($qrcode['status'] == '2000'){
                foreach ($qrcode['result'] as $key => $value){

                    $data = array(
                        'send_weixin_data' => array(
                            'touser' => $value['open_id'],//要发给谁
                            //'touser_platform' => 1,//微信1（目前只有微信，写死为1）
                            'template_id' => '0agp55PIHYazsOBYc1dd3lBwoC1BEZkPDbAY5KywUUc',
                            'url'=>'http://test.weixin2.mayi121.com/succPayDetail?order_num='.$value['order_num'],
                            'topcolor'=>"#FF0000",
                            'data'=>array(
                                'first'=>array('value'=>"收款通知","color"=>"#173177"),
                                'OrderSn'=>array('value'=>$orderInfo['result'][0]['order_num'],"color"=>"#173177"),
                                'OrderAmount'=>array('value'=>$orderInfo['result'][0]['amount'],"color"=>"#173177"),
                                'OrderName'=>array('value'=>$orderInfo['result'][0]['product_name'],"color"=>"#173177"),
                                'remark'=>array('value'=>"\n您已收款成功","color"=>"#173177"),
                            )
                        ),
                    );

                    $weixin =  new \Lib_Weixin();
                    $tokenarr = $weixin->getAccessToken(WXAPPID, APPSECRET);
                    $weixin->sendTemplateMessage($tokenarr['access_token'],$data['send_weixin_data']);
                }

            }

        }
        //工行异步通知后推送消息,所以请勿返回中断。

    }


    /**
     * 推送微信信息-机构充值成功
     *
     */
    public function partnerSendWeChat(){

        $params = request()->param();
//        $orderInfo['result'][0]['open_id'] = 'oHRftt6_uBpTa1q81GcHl1OIMwf0';
//        $orderInfo['result'][0]['order_num'] = 'MY201811122042563961';
//        $orderInfo['result'][0]['product_name'] = '设计师全能VIP套餐（4合1）';

        //查询订单 order_type
        $orderInfo = $this->getWS('credit', 'Aggregate@getOrderList', ['order_num'=>$params['order_num'],'order_type'=>2]);
        if ($orderInfo['status'] == '2000') {
            //推送机构绑定人员信息
            $data = array(
                'partner_id'    => $orderInfo['result'][0]['partner_id'],
                'qrcode_type'   => 3,
                'is_delete'     => 2,
            );
            $qrcode = $this->getWS('credit', 'PartnersQrcode@partnerSelect', $data);

            if($qrcode['status'] == '2000'){
                foreach ($qrcode['result'] as $key => $value){

                    $data = array(
                        'send_weixin_data' => array(
                            'touser' => $value['open_id'],//要发给谁
                            //'touser_platform' => 1,//微信1（目前只有微信，写死为1）
                            'template_id' => '0agp55PIHYazsOBYc1dd3lBwoC1BEZkPDbAY5KywUUc',
                            'url'=>'http://test.weixin2.mayi121.com/succPayDetail?order_num='.$value['order_num'],
                            'topcolor'=>"#FF0000",
                            'data'=>array(
                                'first'=>array('value'=>"充值提醒","color"=>"#173177"),
                                'OrderSn'=>array('value'=>$orderInfo['result'][0]['order_num'],"color"=>"#173177"),
                                'OrderAmount'=>array('value'=>$orderInfo['result'][0]['amount'],"color"=>"#173177"),
                                'OrderName'=>array('value'=>$orderInfo['result'][0]['partner_name'],"color"=>"#173177"),
                                'remark'=>array('value'=>"\n您已充值成功","color"=>"#173177"),
                            )
                        ),
                    );
                    $weixin =  new \Lib_Weixin();
                    $tokenarr = $weixin->getAccessToken(WXAPPID, APPSECRET);
                    $weixin->sendTemplateMessage($tokenarr['access_token'],$data['send_weixin_data']);
                }

            }

        }
        //工行异步通知后推送消息,所以请勿返回中断。

    }

    /**
     * 推送微信信息-用户支付成功
     * http://release.weixin.mayi121.com/userSendWeChat?type=1&order_num='MY201811122042563961'
     * http://release.weixin.mayi121.com/userSendWeChat?type=2&order_num='MY201811122042563961'
     * $url = "http://release.weixin.mayi121.com/userSendWeChat?type=1&open_id=".$orderSelect['result'][0]['open_id']."&order_num=".$orderSelect['result'][0]['order_num'];
     */
    public function userSendWeChat(){

        $params = request()->param();
        Log::write($params, '微信发送信息', true, 'weixin/');
//        $params['open_id']='oHRftt1aVBo7g40a3RPafQI8HTGc';
//        $params['order_num'] = 'MY201811122042563961';
//        $params['amount'] = '0.01';

        $orderInfo['result'][0]['open_id']=$params['open_id'];
        $orderInfo['result'][0]['order_num'] = $params['order_num'];
        $orderInfo['result'][0]['amount'] = $params['amount'];
        $orderInfo['result'][0]['add_time'] = date('Y-m-d H:i:s');

//        Log::write($orderInfo, '微信发送信息1', true, 'weixin/');
        //type = 1 用户支付
        if($params['type'] == 1){

            $orderInfo = $this->getWS('credit', 'PartnersOrder@orderPartnerInfo', ['order_num'=>$params['order_num']]);
            Log::write($orderInfo, '微信发送信息1', true, 'weixin/');
            //查询机构收款人信息
            $data = array(
                'partner_id'    => $orderInfo['result']['partner_id'],
                'qrcode_type'   => 1,
                'is_delete'     => 2,
            );
            $qrcode = $this->getWS('credit', 'PartnersQrcode@partnerSelect', $data);
            Log::write($qrcode, '微信发送信息2', true, 'weixin/');

            //这里循环发送给机构关注人，最多5个
            foreach ($qrcode['result'] as $key=>$value) {
                //发送机构收款人信息
                $data = array(
                    'touser' => $value['open_id'],//要发给谁
                    'template_id' => 'TQCuxs0U_oa3zDi7dhj5M0lXkI25jKAG2Hu-YEYnLAw',
                    'url'=>'http://my.admin.mayi121.com',
                    'topcolor'=>"#FF0000",
                    'data'=>array(
                        'first'=>array('value'=>$orderInfo['result']['phone'].'付款信息',"color"=>"#173177"),//
                        'keyword1'=>array('value'=> $orderInfo['result']['amount'],"color"=>"#173177"),//收款金额
                        'keyword2'=>array('value'=> '工蚂付',"color"=>"#173177"),//收款类型
                        'keyword3'=>array('value'=> date('Y-m-d H:i:s'),"color"=>"#173177"),//收款日期
                        'remark'=>array('value'=>"\n您已收款成功","color"=>"#173177"),
                    )
                );
                Log::write($data, '微信发送信息3', true, 'weixin/');
                $this->getWS('channel', 'wechat@sendMessageTest', $data);
            }

            //发送学员微信通知
            $data = array(
                'touser' => $orderInfo['result']['open_id'],//要发给谁
                'template_id' => '8MjZ0DB4fnvMTDQsIaipS7d531JQXbyHqG48Gu94-PI',
                'url'=>'http://release.weixin.mayi121.com/succPayDetail?order_num='.$orderInfo['result']['order_num'],
                'topcolor'=>"#FF0000",
                'data'=>array(
                    'first'=>array('value'=>"支付提醒","color"=>"#173177"),//
                    'keyword1'=>array('value'=>$orderInfo['result']['order_num'],"color"=>"#173177"),//订单编号
                    'keyword2'=>array('value'=>$orderInfo['result']['product_name'],"color"=>"#173177"),//商品名称
                    'keyword3'=>array('value'=>$orderInfo['result']['amount'],"color"=>"#173177"),//订单总价
                    'keyword4'=>array('value'=>'成功',"color"=>"#173177"),//订单状态
                    'keyword5'=>array('value'=> $orderInfo['result']['add_time'],"color"=>"#173177"),//下单时间
                    'remark'=>array('value'=>"\n您已支付成功","color"=>"#173177"),
                )
            );
            Log::write($data, '微信发送信息4', true, 'weixin/');
        }else if($params['type'] == 2){//机构充值
            $data = array(
                'touser' => $params['open_id'],//要发给谁
                'template_id' => '0agp55PIHYazsOBYc1dd3lBwoC1BEZkPDbAY5KywUUc',
                'url'=>'http://my.admin.mayi121.com/admin/account/account_detail_details.html?order_num='.$params['order_num'],
                'topcolor'=>"#FF0000",
                'data'=>array(
                    'first'=>array('value'=>"充值提醒","color"=>"#173177"),
                    'keyword1'=>array('value'=>$params['order_num'],"color"=>"#173177"),
                    'keyword2'=>array('value'=>$params['amount'],"color"=>"#173177"),
                    'keyword3'=>array('value'=>'账户充值',"color"=>"#173177"),
                    'remark'=>array('value'=>"\n您已充值成功","color"=>"#173177"),
                )
            );
        }
        $this->getWS('channel', 'wechat@sendMessageTest', $data);

    }


    /**
     * 推送微信信息-测试
     * http://release.weixin.mayi121.com/testSendWeChat?openid='oHRftt6_uBpTa1q81GcHl1OIMwf0'&order='MY201811122042563961'&money='0.01'
     */
    public function testSendWeChat(){

        $params = request()->param();

        $params['open_id']='oHRftt6_uBpTa1q81GcHl1OIMwf0';
        $params['order_num'] = 'MY201811122042563961';
        $params['amount'] = '0.01';
        $params['add_time'] = date('Y-m-d H:i:s');

        $sendMsg = array(
            'touser' => $params['open_id'],//要发给谁
            'template_id' => '0agp55PIHYazsOBYc1dd3lBwoC1BEZkPDbAY5KywUUc',
            'url'=>'http://test.weixin2.mayi121.com/succPayDetail?order_num='.$params['order_num'],
            'topcolor'=>"#FF0000",
            'data'=>array(
                'first'=>array('value'=>"充值提醒","color"=>"#173177"),
                'keyword1'=>array('value'=>$params['order_num'],"color"=>"#173177"),
                'keyword2'=>array('value'=>$params['amount'],"color"=>"#173177"),
                'keyword3'=>array('value'=>'账户充值',"color"=>"#173177"),
                'remark'=>array('value'=>"\n您已充值成功","color"=>"#173177"),
            )
        );

        $ret = $this->getWS('channel', 'wechat@sendMessageTest', $sendMsg);
        
    }


    /**
     * 易宝支付方式-这里代替连连支付
     *
     **/
    public function yeePay()
    {
        $params = request()->param();
        //判断订单信息
        if(empty($params['b_id']) || empty($params['period_no'])){
            return $this->parse_data(['code' => 5000, 'msg' => '信息有误！']);
        }

        $repayment = $this->getWS('credit', 'repayment@checkRepayment', ['b_id' => $params['b_id']]);
        if($repayment['status'] != '2000'){
            return $this->parse_data(['code' => 5000, 'msg' => $repayment['msg']]);
        }
        if($repayment['result']['period_no'] != $params['period_no']){
            return $this->parse_data(['code' => 5000, 'msg' => '请您先交费上一期账单']);
        }
        //订单信息
        $order = $this->getWS('credit', 'apply@applyInfo', ['b_id' => $params['b_id']]);
        if($order['status'] != '2000'){
            return $this->parse_data(['code' => 5000, 'msg' => '交费失败']);
        }

        // 查询商户渠道报备号
        $partnerChannel = $this->getWS('credit', 'partners@partnerChannel', ['partner_id'=>$order['result']['partner_id']]);
        if($partnerChannel['status'] != '2000' || empty($partnerChannel['result']['partner_yee_no'])){
            return $this->parse_data(['code'=>'5000','msg'=>'查询错误']);
        }

        $res = $this->getWS('credit', 'repayment@repaymentAmt', ['b_id' => $params['b_id'], 'period_no' => $params['period_no']]);
        if ($res['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '订单信息有误']);
        }
        $order_num = 'YH'.date('YmdHis').mt_rand(1000,9999);
//        $order_num = 'YH201903251850488683';

        //用户主动支付下单
        $transactionPay = array(
            'order_type'        => '4',//订单类型：1、聚合支付，2机构充值。3首付,4用户主动还款
            'channel'           => '4',//第三方通道：1学通宝，2招商 3工商4易宝
//            'appid'             => $partnerChannel['result']['partner_yee_no'],//商户报备号
            'appid'             => '10026053357',//商户报备号
            'u_code'            => $order['result']['u_code'],//客户编号
            'b_id'              => $params['b_id'],//进件id
            'period_no'         => $params['period_no'],//第几期
            'partner_id'        => $order['result']['partner_id'],//商户id
            'partner_name'      => $order['result']['partner_name'],//商户名称
            'order_num'         => $order_num,//订单号
            'services'          => '',//服务类型
            'amount'            => sprintf("%1\$.2f", $res['result']['repaymentAmt']),//交易金额
            'product_id'        => $order['result']['p_id'],//课程id
            'product_name'      => $order['result']['p_name'],//产品名称
            'name'              => $order['result']['u_true_name'],//姓名
            'phone'             => $order['result']['u_name'],//手机号
            'note'              => '',//备注
            'status'            => '1000',//状态：1000初始，2000成功，3000等待，4000失败
            'add_time'          => date('Y-m-d H:i:s'),//下单时间
            'clientip'          => getenv("REMOTE_ADDR"),//请求IP地址
            'open_id'           => $order['result']['open_id'],//微信用户唯一标识 session('openid')
        );

        $partnersOrder = $this->getWS('credit', 'PartnersOrder@partnerInsert', $transactionPay);
        if ($partnersOrder['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '下单失败']);
        }

        //查询订单
        $orderInfo = $this->getWS('credit', 'PartnersOrder@partnerSelect', ['order_num'=>$order_num]);
        if ($orderInfo['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '下单失败,请联系管理员']);
        }
//        print_r($orderInfo);exit;
        //判断是否是微信还是支付宝
        if(IsWeixinOrAlipay() == 'WeiXin'){
            $services = 1;
        }else if(IsWeixinOrAlipay() == 'Alipay'){
            $services = 2;
        }else{
            $services = 3;
        }

        // type 字段为区分支付流程 同步通知路径
        return view('pay/yee_pay',
            [
                'data'=>$orderInfo['result'][0],
                'services'=>$services,
            ]);
    }


    /**
     * 确认支付页面(易宝)
     *
     **/
    public function determineYeePay($params){

        //判断用户是否登录
        if (!session('username')) {
            return $this->parse_data(['code' => 5003, 'msg' => '请先登录']);
        }
        //验证信息
        if(empty($params['order_num']) || empty($params['u_code']) || empty($params['services'])){
            return $this->parse_data(['code' => 5000, 'msg' => '数据不能为空']);
        }

        //查询订单
        $orderInfo = $this->getWS('credit', 'Aggregate@getOrderList', ['order_num'=>$params['order_num']]);
        if ($orderInfo['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '支付失败,请联系管理员']);
        }

        //判断是否是微信还是支付宝
        if($params['services'] == 1){
            $services = $params['services'];
            $payType = 'WECHAT';
            $payTool = 3;
            $payRate = 0.68;
        }else if($params['services'] == 2){
            $services = $params['services'];
            $payType = 'ALIPAY';
            $payTool = 1;
            $payRate = 0.68;
        }else if($params['services'] == 3){
            $services = $params['services'];
            $payType = 'UPOP';
            $payRate = 0.45;
        }else{
            return $this->parseData(["code"=>500,"msg"=>"请选择支付方式！",'closeCurrTab'=>false]);
        }

        //根据支付类型  扣除易宝交易手续费  进行订单分账
        $divide_detail_info = $this->divideDetailInfo(['id'=>$orderInfo['result'][0]['id'],'b_id'=>$orderInfo['result'][0]['b_id'],'period_no'=>$orderInfo['result'][0]['period_no'],'partner_id'=>$orderInfo['result'][0]['partner_id'],'payRate'=>$payRate]);

        //选择支付类型，1微信2支付宝，3银联
        $redirectUrl = "http://test.weixin2.mayi121.com/paySuccess?order_num=".$orderInfo['result'][0]['order_num'];
        $redirectUrl = empty($params['redirectUrl']) ? $redirectUrl : $params['redirectUrl'];
        if($services == '3'){
            //调用易宝接口支付
            $yeeData = array(
                'merchantNo'    => $orderInfo['result'][0]['appid'],//子商编（业务上是必须参数，收单商户商编）10015004197
                'orderId'       => $orderInfo['result'][0]['order_num'],//商户请求号（业务上是必须参数，商户订单号）
                'orderAmount'   => $orderInfo['result'][0]['amount'],//总金额（单位：分）
                'userNo'        => $orderInfo['result'][0]['u_code'],//用户标识
                'redirectUrl'   => $redirectUrl, //支付成功回显页面
                'productName'   => $orderInfo['result'][0]['product_name'], // 产品名称
                'productDesc'   => $orderInfo['result'][0]['product_name'], // 产品描述
                'divide_detail_info' => json_encode($divide_detail_info)  //分账明细
            );

            Log::write($yeeData, '易宝接口返回4', true, 'yee/');
            $yeePay = $this->getWS('channel', 'Yeepay@payment', $yeeData);
            Log::write($yeePay, '易宝接口返回5', true, 'yee/');

            if ($yeePay['status'] != '2000') {
                return $this->parse_data(['code' => 5000, 'msg' => '支付失败!','closeCurrTab'=>false]);
            }

            //成功后写入同步信息
            $data = array(
                'order_num'         => $orderInfo['result'][0]['order_num'],
                'status'            => '3000',
                'services'          => $services,
                'synchronize_info'  => serialize($yeePay),//同步信息
            );
            $updateOrder = $this->getWS('credit', 'Aggregate@updateOrderStatus', $data);
            if($updateOrder['status'] != "2000"){
                return $this->parse_data(['code' => 5000, 'msg' => '同步信息写入失败!','closeCurrTab'=>false]);
            }

            //处理接受到的信息（因为这里&符号到html前端会转义，需要处理下。）
            $url = strtr($yeePay['result'], '&', '&amp;');

            return $this->parse_data(['code' => 2000, 'data' => ['pay' => $url]]);
        }else if($services == 1 || $services == 2){
            //调用易宝接口支付
            $yeeData = array(
                'merchantNo'    => $orderInfo['result'][0]['appid'],//子商编（业务上是必须参数，收单商户商编）10015004197
                'orderId'       => $orderInfo['result'][0]['order_num'],//商户请求号（业务上是必须参数，商户订单号）
                'orderAmount'   => $orderInfo['result'][0]['amount'],//总金额（单位：分）
                'userNo'        => $orderInfo['result'][0]['u_code'],//用户标识
                'openId'        => $orderInfo['result'][0]['open_id'],//用户OPENID
                'payTool'       => $payTool,//1（用户扫码支付）2（商户扫码支付）3（公众号支付）4（支付宝生活号）5（微信小程序）6（SDK支付）
                'payType'       => $payType,
                'redirectUrl'   => $redirectUrl, //支付成功回显页面
                'productName'   => $orderInfo['result'][0]['product_name'], // 产品名称
                'productDesc'   => $orderInfo['result'][0]['product_name'], // 产品描述
                'divide_detail_info' => json_encode($divide_detail_info)  //分账明细
            );

            Log::write($yeeData, '易宝接口返回1', true, 'yee/');
            $yeePay = $this->getWS('channel', 'Yeepay@pay', $yeeData);
            Log::write($yeePay, '易宝接口返回2', true, 'yee/');

            if ($yeePay['status'] != '2000') {
                return $this->parse_data(['code' => 5000, 'msg' => '支付失败!','closeCurrTab'=>false]);
            }

            //成功后写入同步信息
            $data = array(
                'order_num'         => $orderInfo['result'][0]['order_num'],
                'status'            => '3000',
                'services'          => $services,
                'synchronize_info' => serialize($yeePay),//同步信息
            );
            $updateOrder = $this->getWS('credit', 'Aggregate@updateOrderStatus', $data);
            if($updateOrder['status'] != "2000"){
                return $this->parse_data(['code' => 5000, 'msg' => '支付失败!','closeCurrTab'=>false]);
            }

            //如果是微信返回前端处理微信支付
            if($yeePay['result']['payType'] == 'WECHAT'){

                $wechat = array(
                    'resultData'=>json_decode($yeePay['result']['resultData'],true),
                    'order_num'=>$orderInfo['result'][0]['order_num'],
                );
                Log::write($wechat, '易宝接口返回3', true, 'yee/');
                return $this->parse_data(['code' => 2000, 'data' => ['pay' => $wechat]]);
            }else{//支付宝
                return $this->parse_data(['code' => 2000, 'data' => ['pay' => $yeePay['result']['resultData']]]);
            }
        }else{
            return $this->parse_data(['code' => 5000, 'msg' => '失败!','closeCurrTab'=>false]);
        }

    }


    /**
     * 订单分账(易宝)
     *
     **/
    public function divideDetailInfo($params)
    {
        //根据支付类型  扣除易宝交易手续费  进行订单分账
        $order = $this->getWS('credit', 'apply@applyInfo', ['b_id' => $params['b_id']]);
        if ($order['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '交费失败']);
        }
        $partnerChannel = $this->getWS('credit', 'partners@partnerChannel', ['partner_id' => $params['partner_id']]);
        if ($partnerChannel['status'] != '2000' || empty($partnerChannel['result']['partner_yee_no'])) {
            return $this->parse_data(['code' => '5000', 'msg' => '查询错误']);
        }

        $res = $this->getWS('credit', 'repayment@repaymentAmt', ['b_id' => $params['b_id'], 'period_no' => $params['period_no']]);
        if ($res['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '订单信息有误']);
        }

        $mayi_amout = 0;
        $partner_amout = 0;
        $yeeAmt = sprintf('%.2f', $res['result']['repaymentAmt'] * $params['payRate'] / 100);  //计算易宝手续费金额

        //根据商户或用户支付服务费   取产品表或还款表服务费字段
        $p_service_price = $order['result']['p_partner_service'] ? $order['result']['p_service_price'] : $res['result']['r_service_fee'];
        //验证机构服务费收取方式
        if($order['result']['b_service_mode'] == 2){
            //扣除机构服务费  若机构余额不足进行处理（待定）

            //是否商户收息
            if($order['result']['p_partner_interest_charges']){
                $mayi_amout = 0;
                $partner_amout = $res['result']['r_capital'] + $res['result']['r_interest'] - $yeeAmt;//本金+利息-易宝交易手续费
            }else{
                $mayi_amout = $res['result']['r_interest'];//利息
                $partner_amout = $res['result']['r_capital'] - $yeeAmt;//本金-易宝交易手续费
            }
        }else{
            //是否商户收息
            if($order['result']['p_partner_interest_charges']){
                $mayi_amout = $p_service_price + $res['result']['r_expired_amount'];//服务费+逾期费
                $partner_amout = $res['result']['r_capital'] + $res['result']['r_interest'] -$p_service_price -  $yeeAmt;//本金+利息-服务费-易宝交易手续费
            }else{
                $mayi_amout = $p_service_price + $res['result']['r_expired_amount'] + $res['result']['r_interest'];//服务费+逾期费+利息
                $partner_amout = $res['result']['r_capital'] -$p_service_price -  $yeeAmt;//本金-服务费-易宝交易手续费
            }
        }

        $divide_detail_info = [
            [
                'ledgerNo' => '10025852870', //主商编
                'ledgerName' => '蚂蚁白领',
                'amount' => sprintf("%1\$.2f", $mayi_amout),
            ],
            [
                'ledgerNo' => $partnerChannel['result']['partner_yee_no'], //机构商编
                'ledgerName' => $partnerChannel['result']['partner_name'],
                'amount' => sprintf("%1\$.2f", $partner_amout),
            ]
        ];
        $partnersOrder = $this->getWS('credit', 'PartnersOrder@partnerInsert', ['id' => $params['id'], 'divide_detail_info' => json_encode($divide_detail_info)]);
        if ($partnersOrder['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '支付失败']);
        }
        return $divide_detail_info;
    }

}
